<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php


class CDbConn
{
    
    static private $_instance = null;

    private $link = false;
    private $userTableName;
    private $userSource;

    
    private function  __construct() {
        $this->connect();
    }



    
    static public function getInstance() {
        if (is_null(self::$_instance) || !isset(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public function getCon(){
        return $this->link;
    }

    
    public function getUserSource(){
        return $this->userSource;
    }


    
    public function reConnect(){
        $this->connect();
    }

    
    public function getUserTableName(){
        return $this->userTableName;
    }


    
    public function selectDb($sql)
    {
        $result = mysql_query($sql, $this->link);

        $ret_array = array();
        if ($result === false)
        {
            return $ret_array;
        }

        while ($row = mysql_fetch_assoc($result))
        {
            array_push($ret_array, $row);
        }

                                mysql_free_result($result);

        return $ret_array;
    }


    
    private function connect(){
        $option = new OptionViewForm();
        $userDbSource = $option->getOptionValue("user_db_source");
        $this->userSource = $userDbSource;

        $dbAddress   = $option->getOptionValue($userDbSource."_db_address");
        $dbUserName    = $option->getOptionValue($userDbSource."_user_name");
        $dbPassword    = $option->getOptionValue($userDbSource."_password");
        $dbName      = $option->getOptionValue($userDbSource."_db_name");
        $tablePrefix = $option->getOptionValue($userDbSource."_table_prefix");


        $dbObject = new CMysqlDbConnection();
        $link = $dbObject->connect($dbAddress, $dbUserName, $dbPassword);
        if (!$link) {
            return false;
        }

        $isExistDb = $dbObject->select_db($dbName,$link);
        if (!$isExistDb){
            return false;
        }

        $userTableName = $this->redeclareUserTableName($userDbSource, $tablePrefix);
        $this->userTableName = $userTableName;
        $isExistUserTable = $dbObject->isExistUser($userTableName);

        if (!$isExistUserTable) {
            return false;
        }
        $this->link = $link;
    }


    
    private function  redeclareUserTableName($userDbSource, $tablePrefix){
        if ($userDbSource == "wordpress"){
            return $tablePrefix."users";
        }elseif ($userDbSource == "phpwind"){
            return $tablePrefix."members";
        }elseif ($userDbSource == "discuz"){
            return $tablePrefix."ucenter_members";
        }
        return "";
    }


}
?>